package cn.wzy.interceptor;

import cn.wzy.annotation.AnPermission;
import cn.wzy.enums.AppHttpCodeEnum;

import cn.wzy.mapper.EmployeeMapper;
import cn.wzy.pojo.Employee;
import cn.wzy.results.ResponseResult;
import cn.wzy.utils.RedisCache;
import cn.wzy.utils.WebUtils;
import com.alibaba.fastjson.JSON;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Objects;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    private RedisCache redisCache;
    @Resource
    private EmployeeMapper employeeMapper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        允许跨域
        //如果是OPTIONS请求的话 进行直接放行
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())){
            System.out.println("OPTIONS请求放行");
            return true;
        }
        String token = request.getHeader("token");
//        从rides中获取用户信息
        Employee user = redisCache.getCacheObject("User:" + token);
        if (Objects.isNull(user)){
//            未登入
            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            WebUtils.renderString(response, JSON.toJSONString(result));
            return false;
        }

//        权限判断
        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod)handler;
            Method method = handlerMethod.getMethod();
//            判断该接口是否有权限注解
            AnPermission annotation = method.getAnnotation(AnPermission.class);
            if (Objects.isNull(annotation)){
                return true;
            }
//            获取到接口资源
            String sn = method.getDeclaringClass().getSimpleName()+":"+method.getName();
//            获取到用户权限信息
            List<String> roleSn = employeeMapper.getPermissionSnById(user.getId());
//            判断用户是否拥有该接口权限
            if (!roleSn.contains(sn)){
                ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
                WebUtils.renderString(response, JSON.toJSONString(result));
                return false;
            }
        }
        return true;
    }
}
